<template>
  <div>
    <el-form label-width="80px" :model="list">

      <el-form-item class="item" label="账号">
        <el-input v-model="list.username" style="width: 30%"></el-input>
      </el-form-item>

      <el-form-item class="item" label="密码">
        <el-input v-model="list.password" style="width: 30%"></el-input>
      </el-form-item>

      <el-form-item class="item" label="姓名">
        <el-input v-model="list.name" style="width: 30%"></el-input>
      </el-form-item>
      <el-form-item class="item" label="权限">
        <el-input v-model="list.role" style="width: 30%"></el-input>
      </el-form-item>


      <el-form-item label="用户头像">
        <!-- 头衔缩略图 -->
        <template slot-scope="scope">
          <el-image v-show="list.salt" :src="list.salt" style="width: 20%;height: 20%"></el-image>
          <!-- 文件上传按钮 -->
          <!--这个吊毛不经过axios必须写全服务器的地址-->
          <el-upload
            :limit=1
            class="upload-demo"
            action="http://127.0.0.1:9002/upload/avatar/"
            multiple
            :on-success="
            (res) => {
              return  (uploadSuccess(res))
             }"
          >

            <el-button size="small" type="primary">点击上传</el-button>

            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </template>
        <el-form-item label="开始实时人脸上传">
          <video id="video" width="450" height="300" src="" autoplay></video>
          <canvas id="canvas" width="450" height="300"></canvas>
        </el-form-item>

      </el-form-item>
      <el-form-item label="人脸上传">
        <video v-show="flag" id="video" width="450" height="300" src="" :autoplay="flag"></video>
        <canvas id="canvas" width="450" height="300"></canvas>
        <el-button v-show="flag" @click="btn()">拍照</el-button>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click=" saveOrUpdate() " style="width: 300px">立即创建</el-button>
        <el-button style="width: 200px">取消</el-button>
      </el-form-item>


    </el-form>
  </div>
</template>
<script>
import UserApi from '@/api/acl'
import face from "../../api/face";

export default {
  data() {
    return {
      flag: true,
      list: {//传回去的集合
        faceBase: '',//照片
        role: '',//角色
        id: '',//id
        name: '',//姓名
        username: '',//用户名
        salt: '',//头像
        password: ''//密码
      }

    }
  },

  created() {
    this.init()
    this.getVideo()
  },

  watch: {
    $route(to, from) {//路有变化的方式  路由发生变化就会执行
      this.init()
    }
  },

  methods: {
    //调用摄像头
    getVideo() {
      /**调用摄像头，获取媒体视频流**/
        //vigator.getUserMedia() 方法提醒用户需要使用音频（0 或者 1）和（0 或者 1）视频输入设备
      let getUserMedia = navigator.getUserMedia
      getUserMedia.call(navigator, {
          video: true,
          audio: false
        },
        // 调用成功
        function (localMediaStream) {
          //获取摄像头捕捉的视频流
          // console.log("获得摄像头")
          document.getElementById('video').srcObject = localMediaStream;
        },
        //调用失败
        function () {
          console("请给摄像头权限")
        });
    },
    //点击按钮注册事件
    //点击按钮时拿到登陆者面部信息
    btn() {
      if (this.list.username != null) {
        //返回画布二维画图环境
        //getContext() 方法可返回一个对象，该对象提供了用于在画布上绘图的方法和属性。
        let userContext = (document.getElementById('canvas')).getContext("2d");
        //向画布上绘制图像、画布或视频
        userContext.drawImage(document.getElementById('video'), 0, 0, 450, 300);
        this.flag = false
        //转化为data URL的格式
        let userImgSrc = document.getElementById("canvas").toDataURL("img/png");
        //拿到bash64格式的照片信息
        let faceBase = userImgSrc.split(",")[1];
        this.list.faceBase = faceBase
        console.log(this.list.faceBase)
      }

    },
    //上传后回调
    uploadSuccess(res) {
      this.list.salt = res.data.urlPath

    },
    /**
     * 通过ID初始化值
     * @param id
     */

    getInfo(id) {
      UserApi.getUserById(id)
        .then(response => {
          this.list = response.data.user
        })
    },

    /**
     * 判断路径是否有id
     */

    upload() {
      UserApi.Upload(this.file)
        .then(response => {
        })
    },

    init() {
      if (this.$route.params && this.$route.params.id) {
        const id = this.$route.params.id
        this.getInfo(id)
      } else {
        this.list = {}
      }
    },

    /**
     * 根据User是否有id
     * 判断修改还是添加
     */
    saveOrUpdate() {

      if (this.list.id) {
        //  添加
        this.updateUser()
      } else {
        this.saveUser()
      }

    },

    //添加航班信息
    saveUser() {
      //调用接口
      face.faceRegister(this.list)
        .then(response => {
          if (response.message == '1') {
            this.$message({
              type: 'success',
              message: '添加成功!'
            })
            // 路由跳转
            this.$router.push({path: '/admin/list'})

          } else if (response.message == '2') {
            this.$message({
              type: 'warning',
              message: '已被注册!'
            })
          } else {
            this.$message({
              type: 'warning',
              message: '发生未知错误，请重试!'
            })
          }
        })
      //调用增加接口

    },
    updateUser() {
      //调用增加接口
      face.faceUpdater(this.list)
        .then(response => {
          if(response.message='1'){
            this.$message({
              type: 'success',
              message: '修改成功!'
            })
          }
          else{
            console.log("发送错误")
          }


          // 路由跳转
          // this.$router.push({path: '/admin/list'})
        })
    }

  }
}
</script>
<style>


</style>
